﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using EFFC.Frame.Net.Base.Cache;
using EFFC.Frame.Net.Base.Common;
using EFFC.Frame.Net.Base.Data;
using EFFC.Frame.Net.Base.Data.Base;
using EFFC.Frame.Net.Global;
using EFFC.Frame.Net.Module.Extend.EWRA;
using EFFC.Frame.Net.Module.Extend.EWRA.Log;
using EFFC.Frame.Net.Module.Extend.Mqtt;
using ICPFrameLib.Business;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;

namespace XHRPMIS
{
    public class Program
    {
        static string defaulturl = "http://*:85";
        static string default_ssl_path = "root.pfx";
        static string default_ssl_password = "123456";
        public static void Main(string[] args)
        {
            GlobalCommon.Logger = new Log4Net();
            GlobalCommon.ExceptionProcessor = new EWRAExceptionProcessor();
            Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
            var useCache = ComFunc.nvl(MyConfig.GetConfiguration("Server", "UseCache"));
            switch (useCache)
            {
                case "Redis":
                    GlobalCommon.ApplicationCache = RedisCache.Current;
                    break;
                default:
                    GlobalCommon.ApplicationCache = new DefaultCache();
                    break;
            }

            GlobalCommon.StartApplication((cancel) =>
            {
                var t = StartRestAPI(cancel, args);
                var t2 = StartRabbitMQClient(cancel, args);
                Task.WaitAll(t, t2);
            });

        }

        static Task StartRestAPI(CancellationTokenSource cancel, string[] args)
        {
            //设定服务端参数
            //SSL证书
            if (!String.IsNullOrEmpty(MyConfig.GetConfiguration("Server", "SSL_File_Path")))
            {

                var path = MyConfig.GetConfiguration("Server", "SSL_File_Path");
                if (File.Exists(path))
                {
                    default_ssl_path = path;
                }
            }
            if (!String.IsNullOrEmpty(MyConfig.GetConfiguration("Server", "SSL_Password")))
            {
                default_ssl_password = MyConfig.GetConfiguration("Server", "SSL_Password");
            }
            Console.WriteLine($"服务器启用的SSL文件路径为{default_ssl_path},如果要调整，在appsettings.json中的SSL_File_Path下设定该参数，并确保文件存在");
            //设定监听端口
            if (!String.IsNullOrEmpty(MyConfig.GetConfiguration("Server", "BindUrl")))
            {
                defaulturl = MyConfig.GetConfiguration("Server", "BindUrl");
            }
            else if (args != null)
            {
                if (args.Length > 0 && ComFunc.nvl(args[0]) != "")
                    defaulturl = args[0];
            }
            Console.WriteLine($"服务器启动绑定URL为{defaulturl},如果要调整，请在启动应用时，后面接端口参数，或者在appsettings.json中的Server下设定BindUrl参数（参数优先）");
            defaulturl = defaulturl.Replace("\\", "/");
            var arr = defaulturl.Split(':');
            var port = 80;
            var isHttps = defaulturl.Trim().ToLower().StartsWith("https");
            if (isHttps)
            {
                port = IntStd.IsNotIntThen(arr[arr.Length - 1], 443);
            }
            else
            {
                port = IntStd.IsNotIntThen(arr[arr.Length - 1], 80);
            }

            var ip = arr.Length > 1 ? arr[1].Replace("/", "") : "*";

            var max_size = Int64Std.IsNotInt64Then(MyConfig.GetConfiguration("Server", "MaxRequestBodySize"), -1);

            var host = new WebHostBuilder()
               .UseKestrel(option =>
               {
                   if (max_size < 0)
                       option.Limits.MaxRequestBodySize = null;
                   else
                       option.Limits.MaxRequestBodySize = max_size * 1024 * 1024;

                   var tmpip = IPAddress.Any;
                   var ipa = IPAddress.TryParse(ip, out tmpip) ? tmpip : IPAddress.Any;
                   option.Listen(ipa, port, listenOptions =>
                   {
                       if (isHttps)
                       {
                           if (defaulturl.ToLower().StartsWith("https"))
                           {
                               listenOptions.UseHttps(default_ssl_path, default_ssl_password);
                           }
                       }
                   });
               })
               .UseContentRoot(Directory.GetCurrentDirectory())
               .UseIISIntegration()
               .UseStartup<Startup>()
               .Build();

            return host.RunAsync(cancel.Token);
        }
        static Task StartRabbitMQClient(CancellationTokenSource cancel, string[] args)
        {
            var client = RabbitMQClient.Create("XHRPMIS", "Plugin", new Type[] { typeof(MyRabbitMQLogic) });
            return client == null ? Task.CompletedTask : client.StartAsync(cancel);
        }
    }
}
